<?php


namespace App\HttpController\Api;

use App\Lib\Check\Authorize;
use App\Repositories\Services\ApiNode;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Http\Message\Status;


class Base extends Controller
{
    //系统url链接

    protected $_clientIp;
    protected $memberItem;
    protected $appInfo;
    protected $url;


    public function index(){}

    //action 是控制器的方法
    public function onRequest(?string $action): ?bool
    {

        $this->url = $this->request()->getUri()->getPath();
        $this->url = substr($this->url,1,strlen($this->url));
        $this->_clientIp = $this->request()->getHeaders()['x-real-ip'][0];

        $appid = $this->request()->getHeaderLine('appid');
        $jwt = $this->request()->getHeaderLine('jwt');

        list($status,$msg,$member,$appInfo) = ApiNode::getInstance()->checkNode($this->url,$this->request()->getMethod(),$this->_clientIp,$appid,$jwt);
        if($status != 1){
             $this->ajaxError(0,$msg);
             return false;
        }
        $this->appInfo = $appInfo;
        $this->memberItem = $member;



        return parent::onRequest($action); // TODO: Change the autogenerated stub
    }

    // AJAX 执行成功
    public function ajaxSuccess(array $data = [],string $msg='',int $count = 0)
    {
        $res = [];
        $res['code'] = 200;
        $res['msg'] = $msg ==''?Status::getReasonPhrase(200):$msg;
        $res['count'] = $count;
        $res['data'] = $data;
        $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
        $this->response()->write(json_encode($res, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        $this->response()->end();
    }

    /**
     * ajax 执行失败
     */
    public function ajaxError(int $code= 0, string $msg = '')
    {

        $res = [];
        $res['code'] = $code??Status::CODE_NO_CONTENT;
        $res['msg'] = $msg ==''?Status::getReasonPhrase(Status::CODE_NO_CONTENT):$msg;
        $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
        $this->response()->write(json_encode($res, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        $this->response()->end();
    }



}